#!/usr/bin/env python3
"""
COS+CDN性能监控脚本
监控API性能，为自动扩容提供数据支持
"""

import time
import json
import logging
import requests
from datetime import datetime, timedelta
from collections import defaultdict, deque
import statistics

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class PerformanceMonitor:
    def __init__(self, api_url="http://localhost:8444"):
        self.api_url = api_url
        self.metrics = {
            'total_requests': 0,
            'successful_requests': 0,
            'failed_requests': 0,
            'avg_processing_time': 0,
            'avg_upload_time': 0,
            'avg_download_time': 0,
            'avg_total_time': 0,
            'compression_ratios': deque(maxlen=100),
            'processing_times': deque(maxlen=100),
            'upload_times': deque(maxlen=100),
            'download_times': deque(maxlen=100),
            'total_times': deque(maxlen=100)
        }
        
        # 性能阈值
        self.thresholds = {
            'max_processing_time': 30.0,  # 30秒
            'max_total_time': 40.0,       # 40秒
            'min_compression_ratio': 0.5,  # 50%压缩率
            'max_queue_time': 10.0        # 10秒排队时间
        }
        
        # 扩容建议
        self.scaling_recommendations = []
    
    def record_request(self, response_data):
        """记录请求性能数据"""
        try:
            self.metrics['total_requests'] += 1
            
            if response_data.get('success'):
                self.metrics['successful_requests'] += 1
                
                perf = response_data.get('performance', {})
                
                # 记录各项时间
                processing_time = perf.get('processing_time', 0)
                upload_time = perf.get('upload_time', 0)
                download_time = perf.get('download_time', 0)
                total_time = perf.get('total_time', 0)
                compression_ratio = perf.get('compression_ratio', 0)
                
                self.metrics['processing_times'].append(processing_time)
                self.metrics['upload_times'].append(upload_time)
                self.metrics['download_times'].append(download_time)
                self.metrics['total_times'].append(total_time)
                self.metrics['compression_ratios'].append(compression_ratio)
                
                # 更新平均值
                self._update_averages()
                
                # 检查性能阈值
                self._check_performance_thresholds(response_data)
                
            else:
                self.metrics['failed_requests'] += 1
                
        except Exception as e:
            logger.error(f"记录性能数据失败: {e}")
    
    def _update_averages(self):
        """更新平均性能指标"""
        if self.metrics['processing_times']:
            self.metrics['avg_processing_time'] = statistics.mean(self.metrics['processing_times'])
        if self.metrics['upload_times']:
            self.metrics['avg_upload_time'] = statistics.mean(self.metrics['upload_times'])
        if self.metrics['download_times']:
            self.metrics['avg_download_time'] = statistics.mean(self.metrics['download_times'])
        if self.metrics['total_times']:
            self.metrics['avg_total_time'] = statistics.mean(self.metrics['total_times'])
    
    def _check_performance_thresholds(self, response_data):
        """检查性能阈值并生成扩容建议"""
        perf = response_data.get('performance', {})
        current_time = datetime.now()
        
        # 检查处理时间
        if perf.get('processing_time', 0) > self.thresholds['max_processing_time']:
            self.scaling_recommendations.append({
                'timestamp': current_time.isoformat(),
                'type': 'processing_time_exceeded',
                'value': perf.get('processing_time', 0),
                'threshold': self.thresholds['max_processing_time'],
                'recommendation': '增加GPU服务器数量'
            })
        
        # 检查总时间
        if perf.get('total_time', 0) > self.thresholds['max_total_time']:
            self.scaling_recommendations.append({
                'timestamp': current_time.isoformat(),
                'type': 'total_time_exceeded',
                'value': perf.get('total_time', 0),
                'threshold': self.thresholds['max_total_time'],
                'recommendation': '优化整体架构或增加服务器'
            })
        
        # 检查压缩率
        if perf.get('compression_ratio', 1) < self.thresholds['min_compression_ratio']:
            self.scaling_recommendations.append({
                'timestamp': current_time.isoformat(),
                'type': 'compression_ratio_low',
                'value': perf.get('compression_ratio', 1),
                'threshold': self.thresholds['min_compression_ratio'],
                'recommendation': '优化图片压缩算法'
            })
    
    def get_performance_summary(self):
        """获取性能摘要"""
        success_rate = 0
        if self.metrics['total_requests'] > 0:
            success_rate = (self.metrics['successful_requests'] / self.metrics['total_requests']) * 100
        
        return {
            'timestamp': datetime.now().isoformat(),
            'summary': {
                'total_requests': self.metrics['total_requests'],
                'successful_requests': self.metrics['successful_requests'],
                'failed_requests': self.metrics['failed_requests'],
                'success_rate': round(success_rate, 2)
            },
            'performance': {
                'avg_processing_time': round(self.metrics['avg_processing_time'], 2),
                'avg_upload_time': round(self.metrics['avg_upload_time'], 2),
                'avg_download_time': round(self.metrics['avg_download_time'], 2),
                'avg_total_time': round(self.metrics['avg_total_time'], 2),
                'avg_compression_ratio': round(statistics.mean(self.metrics['compression_ratios']), 2) if self.metrics['compression_ratios'] else 0
            },
            'scaling_recommendations': self.scaling_recommendations[-10:],  # 最近10条建议
            'thresholds': self.thresholds
        }
    
    def get_scaling_plan(self):
        """生成扩容计划"""
        if not self.metrics['total_requests']:
            return {
                'recommendation': 'no_data',
                'servers_needed': 1,
                'reason': '暂无性能数据'
            }
        
        # 基于平均处理时间计算所需服务器数量
        avg_processing_time = self.metrics['avg_processing_time']
        avg_total_time = self.metrics['avg_total_time']
        
        # 假设每个GPU服务器处理一个任务需要30秒
        target_processing_time = 30.0
        
        if avg_processing_time > target_processing_time:
            # 计算需要的服务器数量
            servers_needed = max(1, int(avg_processing_time / target_processing_time) + 1)
            
            return {
                'recommendation': 'scale_up',
                'servers_needed': servers_needed,
                'current_avg_processing_time': round(avg_processing_time, 2),
                'target_processing_time': target_processing_time,
                'reason': f'平均处理时间 {avg_processing_time:.2f}s 超过目标 {target_processing_time}s'
            }
        else:
            return {
                'recommendation': 'maintain',
                'servers_needed': 1,
                'current_avg_processing_time': round(avg_processing_time, 2),
                'target_processing_time': target_processing_time,
                'reason': '性能指标正常，维持当前配置'
            }

def test_api_performance():
    """测试API性能"""
    monitor = PerformanceMonitor()
    
    # 模拟测试请求
    test_files = [
        'test_image_1.jpg',
        'test_image_2.jpg', 
        'test_image_3.jpg'
    ]
    
    print("🧪 开始性能测试...")
    
    for i, test_file in enumerate(test_files):
        print(f"📊 测试 {i+1}/{len(test_files)}: {test_file}")
        
        # 这里应该发送真实的API请求
        # 为了演示，我们模拟响应数据
        mock_response = {
            'success': True,
            'performance': {
                'processing_time': 25 + (i * 5),  # 模拟不同的处理时间
                'upload_time': 0.5 + (i * 0.1),
                'download_time': 0.3 + (i * 0.05),
                'total_time': 26 + (i * 5),
                'compression_ratio': 0.6 + (i * 0.05)
            }
        }
        
        monitor.record_request(mock_response)
        time.sleep(1)  # 模拟请求间隔
    
    # 输出性能摘要
    summary = monitor.get_performance_summary()
    print("\n📈 性能摘要:")
    print(json.dumps(summary, indent=2, ensure_ascii=False))
    
    # 输出扩容建议
    scaling_plan = monitor.get_scaling_plan()
    print("\n🚀 扩容建议:")
    print(json.dumps(scaling_plan, indent=2, ensure_ascii=False))

if __name__ == '__main__':
    test_api_performance()
